package com.chart.web.controller.chart;


import com.chart.chart.domian.req.UListReq;
import com.chart.chart.service.SysUserOpinionService;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUserOpinion;
import com.chart.common.core.domain.entity.UserCoinLog;
import com.chart.common.utils.FileUtils;
import com.chart.common.utils.SecurityUtils;
import com.chart.common.utils.StringUtils;
import com.chart.system.service.IUserCoinLogsService;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.List;

/**
 * 用户意见controller
 *
 * @author 罗继全
 * 2024/9/24 17:30
 */

@RestController
@RequestMapping("/sysUserOpinion")
public class SysUserOpinionController {

    @Autowired
    private SysUserOpinionService sysUserOpinionService;
    @Autowired
    private IUserCoinLogsService userCoinLogsService;

    /**
     * 查询所有用户意见
     *
     * @return
     */

    @PostMapping("/queryUserOpinion")
    public AjaxResult queryUserOpinion(@RequestBody SysUserOpinion userOpinion) {
        List<SysUserOpinion> list = sysUserOpinionService.queryList(userOpinion);

        for (SysUserOpinion sysUserOpinion : list) {
            Integer status = sysUserOpinion.getStatus();
            switch (status) {
                case 0:
                    sysUserOpinion.setStatusInfo("未处理");
                    break;
                case 1:
                    sysUserOpinion.setStatusInfo("已采纳");
                    break;
                case 2:
                    sysUserOpinion.setStatusInfo("未采纳");
                    break;
                default:
                    sysUserOpinion.setStatusInfo("未知");
                    break;
            }
        }
        return AjaxResult.success(list);
    }


    /**
     * 修改用户意见
     *
     * @return
     */

    @PostMapping("/update")
    public AjaxResult updateUserOpinion(@RequestParam Integer status, @RequestParam Integer id,Long userId) {
        // 创建一个 SysUserOpinion 对象以保存更新后的状态和 ID
        SysUserOpinion sysUserOpinion = new SysUserOpinion();
        sysUserOpinion.setId(id);
        sysUserOpinion.setStatus(status);

        // 更新数据库中的用户意见状态
        boolean isUpdated = sysUserOpinionService.updateById(sysUserOpinion);

        // 如果更新成功且状态设置为 1
        if (isUpdated && status == 1) {
         // 获取当前用户的 ID
            UserCoinLog userCoinLog = new UserCoinLog();
            userCoinLog.setCoins(10); // 设置增加的积分
            userCoinLog.setUserId(userId); // 将积分记录与用户关联
            userCoinLogsService.save(userCoinLog); // 保存用户积分记录
        }

        return AjaxResult.success(); // 返回成功响应
    }

//    @PostMapping("/update")
//    public AjaxResult updateUserOpinion(Integer status, Integer id) {
//
//        if (status == 1) {
//            Long userId = SecurityUtils.getUserId();
//            UserCoinLog userCoinLog = new UserCoinLog();
//            userCoinLog.setCoins(4);
//            userCoinLog.setUserId(userId);
//            userCoinLogsService.save(userCoinLog);
//        }
//
//        SysUserOpinion sysUserOpinion = new SysUserOpinion();
//        sysUserOpinion.setId(id);
//        sysUserOpinion.setStatus(status);
//        boolean b = sysUserOpinionService.updateById(sysUserOpinion);
//
//        if (status == 1) {
//            Long userId = SecurityUtils.getUserId();
//            UserCoinLog userCoinLog = new UserCoinLog();
//            userCoinLog.setCoins(4);
//            userCoinLog.setUserId(userId);
//            userCoinLogsService.save(userCoinLog);
//        }
//
//
//        return AjaxResult.success();
//    }


    /**
     * 保存用户意见
     */
//    @PostMapping("savaUserOpinion")
//    public AjaxResult   insertUserOpinion(@RequestBody SysUserOpinion userOpinion){
//
//        List<String> imageUrls = userOpinion.getImageUrls();
//
//
//        Long userId = SecurityUtils.getUserId();
//        SysUserOpinion sysUserOpinion = new SysUserOpinion();
//        sysUserOpinion.setOpinion(userOpinion.getOpinion());
//        sysUserOpinion.setImageUrl(userOpinion.getImageUrl());
//        sysUserOpinion.setUserId(userId);
//        sysUserOpinion.setImageUrl(imageUrls);
//
//        sysUserOpinionService.save(sysUserOpinion);
//        return AjaxResult.success();
//    }
    @PostMapping("savaUserOpinion")
    public AjaxResult insertUserOpinion(@RequestBody SysUserOpinion userOpinion) {
        // 获取用户提供的图片 URL 列表
        List<String> imageUrls = userOpinion.getImageUrls();

        // 获取当前用户 ID
        Long userId = SecurityUtils.getUserId();

        // 创建 SysUserOpinion 实例并设置属性
        SysUserOpinion sysUserOpinion = new SysUserOpinion();
        sysUserOpinion.setOpinion(userOpinion.getOpinion());
        sysUserOpinion.setUserId(userId);
        sysUserOpinion.setCreateTime(LocalDateTime.now());
        // 将图片 URL 列表转换为字符串，假设使用逗号分隔
        if (imageUrls != null && !imageUrls.isEmpty()) {
            String combinedImageUrls = String.join(",", imageUrls);
            sysUserOpinion.setImageUrl(combinedImageUrls); // 将合并后的字符串设置为 imageUrl
        } else {
            sysUserOpinion.setImageUrl(null); // 处理没有图片 URL 的情况
        }

        // 保存用户意见
        sysUserOpinionService.save(sysUserOpinion);
        return AjaxResult.success();
    }


    /**
     * 上传照片
     *
     * @param request
     * @param response
     * @param upload
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @PostMapping("upload")
    public AjaxResult upload(HttpServletRequest request, HttpServletResponse response, @RequestPart(value = "file") MultipartFile file) throws IllegalStateException, IOException {

        //String realPath = "D:/附件";
        String realPath = "/data/dev/public/userOpinion";

        // 判断文件是否为空
        if (!file.isEmpty()) {
            // 文件保存路径
            // 转存文件
            FileUtils.createDirectory(realPath);
            String name = file.getOriginalFilename(); //得到上传文件名称
            String filePath = realPath + "/" + name;  //真实的路径＋名称
            File newFile = FileUtils.getAvailableFile(filePath, 0);//获取可以创建的文件名（如果有同名文件存在，参照Windows系统重命名为xxx(2).xxx)
            file.transferTo(newFile);
            String absolutePath = newFile.getAbsolutePath();
            String suffix = absolutePath.substring(absolutePath.lastIndexOf("."));

            // return "http://202.75.216.132:9999/file/download?source=" + realPath + "/" + newFile.getName();

            // return "http://localhost:10002/sysUserOpinion/download?source=" + realPath + "/" + newFile.getName();

            // return  realPath + "/" + newFile.getName();
            String url ="/static/userOpinion" + "/" + newFile.getName();
            return AjaxResult.success(url);

        }

        return null;
    }

    @RequestMapping("download")
    public void download(@Param("source") String source, HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = new File(source);
        if (file == null || !file.exists()) {
            throw new FileNotFoundException("请求的文件不存在");
        }
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            String agent = (String) request.getHeader("USER-AGENT");
            String fileName = file.getName();
            if (agent != null && agent.indexOf("MSIE") == -1) {
                String enableFileName = "=?UTF-8?B?" + (new String(Base64.getEncoder().encode(fileName.getBytes("UTF-8")))) + "?=";
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
            } else {
                String enableFileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
            }
            out = response.getOutputStream();
            out.write(org.apache.commons.io.FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
